const app = getApp();
Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    var that = this;

    that.setData({
      code: that.options.code
    })
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              //从数据库获取用户信息
              that.getUserInfo();
              //用户已经授权过
              wx.switchTab({
                url: '/pages/index/index'
              })
            }
          });
        }
      }
    })
  },
  bindGetUserInfo: function (e) {
    var that = this
    var code = e.currentTarget.dataset.actionid;
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var info = e.detail.userInfo;
      console.log(info);
      that.getUserInfo(code, info);
      wx.showLoading({ title: '加载中', })
      wx.switchTab({
        url: '/pages/index/index'
      })

    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  },
  //获取用户信息接口
  getUserInfo: function (code, info) {
    var that = this;
    wx.request({
      url: app.d.path + 'Index/user',
      data: {
        openid: app.d.openid,
        img: info.avatarUrl,
        name: info.nickName
      },
      success: function (res) {
        //console.log(res);
        wx.reLaunch({
          url: '/pages/index/index',
        })
       
      },
      fail: function (e) {
        wx.showToast({
          title: '获取用户信息失败！',
          duration: 2000
        });
      },
    });
  },

  globalData: {
    sessionId: null,
    openid: null,
    uname: null,
    name: null,
    sex: null,
    photo: null
  },
})
